﻿using System.Text;

namespace bitzhuwei.JsonFormat {
    static partial class Utility {
        // https://img2024.cnblogs.com/blog/383191/202503/383191-20250318220426747-693528952.png
        /// <summary>
        /// strip off " at start and end of "xxx", and tarnslate escape chars in xxx.
        /// </summary>
        /// <param name="str">"xxx"</param>
        /// <returns></returns>
        internal static bool TryStripOff(this string str, out string result) {
            if (str == null || str == "") { result = ""; return true; }

            var builder = new StringBuilder();
            try {
                var cursor = 1; char current;
                while (cursor < str.Length - 1) {
                    current = str[cursor++];
                    if (false) { }
                    else if (current == '\\') {
                        current = str[cursor++];
                        switch (current) {
                        case '"': builder.Append('"'); break;
                        case '\\': builder.Append('\\'); break;
                        case '/': builder.Append('/'); break;
                        case 'b': builder.Append('\b'); break;
                        case 'f': builder.Append('\f'); break;
                        case 'n': builder.Append('\n'); break;
                        case 'r': builder.Append('\r'); break;
                        case 't': builder.Append('\t'); break;
                        case 'u': {
                            current = str[cursor++];
                            var x = Hex2Number(current) * 16 * 16 * 16;
                            current = str[cursor++];
                            x += Hex2Number(current) * 16 * 16;
                            current = str[cursor++];
                            x += Hex2Number(current) * 16;
                            current = str[cursor++];
                            x += Hex2Number(current);
                            builder.Append((char)x);
                        }
                        break;
                        default: throw new NotImplementedException();
                        }
                    }
                    else { builder.Append(current); }
                }
                result = builder.ToString();
                return true;
            }
            catch (Exception) {
                result = builder.ToString();
                return false;
            }
        }

        private static int Hex2Number(char hex) {
            if (false) { }
            else if ('0' <= hex && hex <= '9') {
                return hex - '0';
            }
            else if ('A' <= hex && hex <= 'F') {
                return hex - 'A' + 10;
            }
            else if ('a' <= hex && hex <= 'f') {
                return hex - 'a' + 10;
            }
            else { throw new NotImplementedException(); }
        }
    }
}

